import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:xbaistack/common/gen.dart';
import 'package:xbaistack/common/toast.dart';

class WebProp {
  final String url;
  final String title;
  WebProp({required this.url, required this.title});
}

class WebViewPage extends BasestatefulWidget<WebProp> {
  const WebViewPage({super.key});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController? _controller;
  int _progressValue = 0;

  // 处理 H5 发来的消息
  void _handleH5Message(String message) {
    final Map<String, dynamic> data = jsonDecode(message);
    print(data['name']);
    Toast.showInfo(data['name']);
    // if (message == 'getUserInfo') {
    //   // 返回用户信息给 H5
    //   // _controller?.runJavaScript(
    //   //   'window.receiveFlutterData(${"{'name': 'John'}"})',
    //   // );
    //   Toast.showInfo('fasdfa');
    // }
    // else if (message == 'closePage') {
    //   Navigator.pop(context);
    // }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final webParams = widget.argumentOf(context);
      final _cont = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        // 添加 JavaScript 通道，命名为 'flutter'（H5 将通过此名调用）
        ..addJavaScriptChannel(
          'flutter', // H5 调用时的对象名
          onMessageReceived: (JavaScriptMessage message) {
            // 处理来自 H5 的消息
            _handleH5Message(message.message);
          },
        )
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              if (!mounted) {
                return;
              }
              debugPrint('WebView is loading (progress : $progress%)');
              setState(() {
                _progressValue = progress;
              });
            },
          ),
        )
        ..loadRequest(Uri.parse('https://www.baidu.com/'));
        // ..loadRequest(Uri.parse('http://127.0.0.1:5500/ceshi.html'));
      // ..loadRequest(Uri.parse(webParams?.url ?? ''));
      setState(() {
        _controller = _cont;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) async {
        // print(didPop);
        if (didPop) return; // 如果已经弹出则直接返回
        final bool canGoBack = await _controller!.canGoBack();
        if (canGoBack) {
          // 网页可以返回时，优先返回上一页
          await _controller!.goBack();
          return Future.value(false);
        }
        if (mounted) {
          Navigator.of(context).pop(result);
        }
      },
      // onWillPop: () async {
      //   final bool canGoBack = await _controller!.canGoBack();
      //   if (canGoBack) {
      //     // 网页可以返回时，优先返回上一页
      //     await _controller!.goBack();
      //     return Future.value(false);
      //   }
      //   return Future.value(true);
      // },
      child: Scaffold(
        appBar: AppBar(
          title: Text('data'),
          actions: [
            IconButton(
              onPressed: () {
                _controller!.reload();
              },
              icon: Icon(Icons.refresh),
            ),
          ],
        ),
        body: Stack(
          children: [
            if (_controller != null) WebViewWidget(controller: _controller!),
            if (_progressValue != 100)
              LinearProgressIndicator(
                value: _progressValue / 100,
                backgroundColor: Colors.transparent,
                minHeight: 2,
              )
            else
              SizedBox.shrink(),
          ],
        ),
      ),
    );
  }
}
